import http from 'node:http'
import fs from 'node:fs'
import url from 'node:url'
const html = fs.readFileSync('./public/reverseProxy.html') //给html文件起个服务
import { createProxyMiddleware } from 'http-proxy-middleware'
import { server as SERVER } from '../public/rp.config.js'
console.log('SERVER', SERVER)
import express from 'express'
/* /reverseProxy */
/* 将客户端的请求转发到一个或多个后端服务器，并将后端服务器的响应返回给客户端。 */
const router = express.Router() //路由模块
router.get('/', (req, res) => {
  const server = http.createServer((req, res) => {
    const { pathname } = url.parse(req.url)
    const proxyList = Object.keys(SERVER.proxy) //获取代理的路径
    if (proxyList.includes(pathname)) {
      //如果请求的路径在里面匹配到 就进行代理
      const proxy = createProxyMiddleware(SERVER.proxy[pathname]) //代理
      proxy(req, res)
      return
    }
    console.log(proxyList)
    res.writeHead(200, {
      'Content-Type': 'text/html',
    })
    res.end(html) //返回html
  })

  server.listen(8088) //监听端口

  http
    .createServer((req, res) => {
      const { pathname } = url.parse(req.url)

      if (pathname === '/api') {
        res.end('success proxy')
      }
    })
    .listen(3000)

  res.json({
    port: 8088,
    proxyPort: 3000,
  })
})

export default router
